import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../controllers/position_controller.dart';



class AddSellRecordPage extends StatefulWidget {
  final String symbol;
  final String name;
  final int availableQuantity;


  const AddSellRecordPage({
    super.key,
    required this.symbol,
    required this.name,
    required this.availableQuantity
  });

  @override
  _AddSellRecordPageState createState() => _AddSellRecordPageState();
}

class _AddSellRecordPageState extends State<AddSellRecordPage> {
  final PositionController _controller = Get.find();
  final _formKey = GlobalKey<FormState>();

  final _priceController = TextEditingController();
  final _quantityController = TextEditingController();

  DateTime _selectedDate = DateTime.now();

  bool _hasSavedSuccessfully = false; // 新增：标记保存成功状态

  @override
  void initState() {
    super.initState();
    _quantityController.text = widget.availableQuantity.toString();

  }

  @override
  void dispose() {
    _priceController.dispose();
    _quantityController.dispose();
    super.dispose();
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
    );

    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  Future<void> _submitForm() async {
    if (_formKey.currentState!.validate()) {
      final price = double.tryParse(_priceController.text);
      final quantity = int.tryParse(_quantityController.text);

      if (price == null || quantity == null) {
        Get.snackbar(
          '错误',
          '请输入有效的价格和数量',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.red[100],
          colorText: Colors.red[900],
        );
        return;
      }

      try {
        // 这里需要获取买入记录ID，简化处理，实际应用中需要选择具体的买入记录
        final buyRecord = _controller.observablePositions
            .firstWhere((p) => p.position.symbol == widget.symbol)
            .position.buyRecords
            .firstWhere((r) => r.remainingQuantity > 0);

        final success = await _controller.sellStock(
          buyRecordId: buyRecord.id,
          sellPrice: price,
          sellQuantity: quantity,
          sellDate: _selectedDate,
        );

        if (success) {
          // 先显示 Snackbar
          Get.snackbar(
            '成功',
            '卖出记录已保存',
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Colors.green[100],
            colorText: Colors.green[900],
            duration: const Duration(seconds: 2),
          );

          print("object");
          // 设置保存成功标志，但不关闭页面
          setState(() {
            _hasSavedSuccessfully = true;
          });
        } else {
          Get.snackbar(
            '错误',
            '保存卖出记录失败',
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Colors.red[100],
            colorText: Colors.red[900],
            duration: const Duration(seconds: 4),
          );
        }
      } catch (e) {
        print("操作失败:$e");
        Get.snackbar(
          '错误',
          '操作失败: $e',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.red[100],
          colorText: Colors.red[900],
          duration: const Duration(seconds: 4),
        );
      }
    }
  }

  // 新增：关闭页面方法
  void _closePage() {
    // 返回保存成功状态，以便上级页面刷新
    Navigator.of(context).pop(_hasSavedSuccessfully);
   // Get.back(result: _hasSavedSuccessfully);
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('卖出 ${widget.name}'),
        backgroundColor: Colors.blue[700],
        foregroundColor: Colors.white,
        leading: IconButton(
          icon: const Icon(Icons.close),
          onPressed: _closePage, // 使用关闭页面方法
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('股票代码: ${widget.symbol}'),
              Text('股票名称: ${widget.name}'),
              Text('可卖出数量: ${widget.availableQuantity}'),
              const SizedBox(height: 16),
              TextFormField(
                controller: _priceController,
                decoration: const InputDecoration(
                  labelText: '卖出价格*',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.attach_money),
                ),
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入卖出价格';
                  }
                  final price = double.tryParse(value);
                  if (price == null || price <= 0) {
                    return '请输入有效的价格';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _quantityController,
                decoration: const InputDecoration(
                  labelText: '卖出数量*',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.format_list_numbered),
                ),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入卖出数量';
                  }
                  final quantity = int.tryParse(value);
                  if (quantity == null || quantity <= 0) {
                    return '请输入有效的数量';
                  }
                  if (quantity > widget.availableQuantity) {
                    return '卖出数量不能超过可卖出数量';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              InkWell(
                onTap: () => _selectDate(context),
                child: InputDecorator(
                  decoration: const InputDecoration(
                    labelText: '卖出日期*',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.calendar_today),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '${_selectedDate.year}-${_selectedDate.month.toString().padLeft(2, '0')}-${_selectedDate.day.toString().padLeft(2, '0')}',
                      ),
                      const Icon(Icons.calendar_today),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 24),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _submitForm,
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                  ),
                  child: const Text('保存卖出记录'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}